<template>
  <div class="incomeRateChart flex-h-sb">
    <div class="chart">
      <div
        v-if="
          fitNetWorth_obj[nameKeyList[0]] &&
          fitNetWorth_obj[nameKeyList[0]].length > 0
        "
      >
        <div
          :id="id"
          :class="className"
          :style="{ height: (height - 40) * 1.6 + 'px', width: width }"
        />
        <div
          :id="`${id}1`"
          :style="{ height: height * 0.72 + 'px', width: width }"
        />
      </div>
      <div
        v-else-if="false"
        class="flex-vh-center"
        style="height: 565px; margin-top: 24px; padding-left: 200px"
      >
        <img style="color: #666" :src="nodata" alt="" />
        <div style="color: #888; margin-top: 16px; font-size: 22px">
          还未选择相关数据
        </div>
        <div style="margin-top: 48px">
          <el-button
            style="height: 48px; width: 180px; font-size: 18px"
            @click="delBoard()"
            >删除看板</el-button
          >
          <el-button
            style="height: 48px; width: 180px; font-size: 18px"
            type="primary"
            @click="addHandle()"
          >
            选择产品
          </el-button>
        </div>
      </div>
      <div
        v-else
        class="flex-vh-center"
        style="height: 565px; margin-top: 24px"
      >
        <img style="color: #666" :src="oldnodata" alt="" />
        <div style="color: #888; font-size: 22px">
          此区间无两个以上净值数据，无法绘制曲线
        </div>
      </div>
      <div
        v-show="
          netWorth_obj[nameKeyList[0]] && netWorth_obj[nameKeyList[0]].length
        "
        class="tip"
      >
        <p>本区间最大回撤：{{ sectionIncomeRate }}</p>
        <p>{{ sectionDate }}</p>
      </div>
    </div>

    <div
      v-if="
        fitNetWorth_obj[nameKeyList[0]] &&
        fitNetWorth_obj[nameKeyList[0]].length > 0
      "
      class="control"
    >
      <div
        v-show="showBeyondIncome"
        class="beyondIncome flex-h-sb flex-v-center"
      >
        <el-input :value="name1" disabled style="width: 45%"></el-input>
        <div class="shortline"></div>
        <el-select
          v-model="beyondIncome_index"
          @change="beyondIncomeHandle"
          style="width: 45%"
        >
          <el-option
            v-for="item in indexNames"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <div class="legend" :class="{ mt16: showBeyondIncome }">
        <div
          class="card flex-h-sb flex-v-center"
          v-for="(item, i) in nameLegends"
          :key="i"
        >
          <div class="left flex-v-center">
            <el-checkbox
              style="margin: 2px 0 0 14px"
              class="flex-v-center"
              :disabled="item.disabled"
              v-model="item.status"
              @change="legendHandle(item.key)"
            ></el-checkbox>
            <!-- @click="checkStatus(item)" -->

            <div class="legend-name">
              <p
                v-if="!item.contrast_type"
                style="padding-left: 6px; color: #333; font-size: 14px"
              >
                {{ item.name }}
              </p>
              <p v-else style="padding-left: 6px">
                {{ legendTypeCom(item.contrast_type) }}{{ item.name }}
              </p>
              <div
                class="line"
                :style="`border: 1px solid ${item.color};`"
              ></div>
            </div>
          </div>
          <div class="right">
            <p>
              {{ legendIncome(item.key) }}（年化
              {{ legendAnnualizedIncome(item.key) }}
              ）
            </p>
            <p>最大回撤：{{ legendMaxBack(item.key) }}</p>
          </div>
        </div>
        <!-- <div
          class="card flex-h-sb flex-v-center"
          v-for="(item, i) in nameLegends"
          :key="i"
          @click="checkStatus(item)"
        >
          <div class="left">
            <div class="legend-name">
              <p>
                <span> {{ item.name }}</span>
              </p>
              <div
                class="line"
                :style="`border: 1px solid ${item.color};`"
              ></div>
            </div>
            <div style="line-height: 18px; margin-top: 6px">
              <p>
                {{ legendIncome(item.key) }}
                （年化 {{ legendAnnualizedIncome(item.key) }}）
              </p>
              <p>最大回撤：{{ legendMaxBack(item.key) }}</p>
            </div>
          </div>
          <div class="right">
            <el-checkbox
              style="margin: 2px 0 0 14px"
              class="flex-v-center"
              v-model="item.status"
              @change="legendHandle(item.key)"
            ></el-checkbox>
          </div>
        </div> -->
        <div>
          <el-button
            v-show="nameLegends.length < 10"
            style="margin: 16px; border: 1px dashed #d9d9d9; width: 400px"
            @click="addHandle()"
          >
            <i class="iconfont icon-add-circle"></i>
            <span> 添加曲线 </span>
          </el-button>
        </div>
      </div>
    </div>
    <!-- <allStrategyOpen
      v-if="addOrUpdateVisible"
      title="添加策略（多选）"
      type="check"
      ref="addOrUpdate"
      :userId="userId"
      :surplusNum="5 - strategyList.length"
      :checkPList="strategyList"
      @selctInvestName="selctInvestNameHandle"
      @selCheckctInvestName="selCheckctInvestNameHandle"
    ></allStrategyOpen> -->
  </div>
</template>

<script>
import * as echarts from "echarts";
import nodata from "@/assets/nodataHome.png";
import oldnodata from "@/assets/nodata.png";

import resize from "@/components/Charts/mixins/resize";

import { delBoard, getBulletinBoardLine } from "@/api/dashboard";
import { parseTime, debounce } from "@/utils";
import { differenceInCalendarMonths } from "date-fns";
// import allStrategyOpen from "./../components/allStrategyOpen.vue";
import { COLORLIST } from "./../const";

import {
  yAxisNumber,
  xReturnZeroFristPage,
  randomStr,
  // getWeekData,
  // getMonthData,
  listAfterClearNull
} from "@/utils/pro";
// import { im } from "mathjs";
export default {
  mixins: [resize],
  // components: {
  //   allStrategyOpen,
  // },
  props: {
    className: {
      type: String,
      default: "chart"
    },
    id: {
      type: String,
      default: "chart"
    },
    bulletinBoardList: {
      type: Array
    },
    width: {
      type: String,
      default: "200px"
    },
    height: {
      type: Number,
      default: 200
    },
    segment: {
      type: Number | String
    },
    year: {
      type: Number | String
    },
    id_index: {
      type: Array,
      default: () => {
        return [];
      }
    },
    typePage: {
      type: String,
      default: ""
    },
    userId: {
      type: String | Number,
      default: ""
    },
    name1: {
      type: String,
      default: "拟合"
    },
    name2: {
      type: String,
      default: "风险"
    },
    indexNames: {
      type: Array,
      default: () => {
        return [];
      }
    },
    strategyList: {
      // 策略列表
      type: Array,
      default: () => {
        return [];
      }
    },
    sameSection: {
      // 同区间
      type: Boolean,
      default: false
    },
    showBeyondIncome: {
      // 超额收益
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      chart: null,
      chart1: null,
      startTime: "",
      endTime: "",

      currentObj1: {},
      currentObj2: {},
      strategyIds: [], // 策略id

      beyondIncome_index: "",

      xDate: [], // y轴
      fitNetWorth_obj: {}, // 收益集合
      netWorth_obj: {}, // 回撤集合

      isIndexList: [], // 记录指数名称数组
      legendStatus: {}, // 记录图例选择状态
      firstInPage: 1, // 记录首次进入页面用

      nameKeyObj: {}, // 曲线名称重复问题，用唯一key记录
      nameKeyList: [], // 唯一key列表
      nameLegends: [], // 自定义图例属性

      day_xDate: [], // 日频y轴
      day_fitNetWorth_obj: {}, // 日频收益集合
      day_netWorth_obj: {}, // 日频回撤集合

      nodata: nodata,
      oldnodata: oldnodata,
      // addOrUpdateVisible: false,

      color_list: COLORLIST
    };
  },
  computed: {
    sectionIncomeRate() {
      if (!this.chart1) {
        return "";
      }
      const key = listAfterClearNull(this.nameLegends[0])[0].key;
      const list = listAfterClearNull(this.currentObj2[key])[0];
      if (!list.length) return "--";
      const min = Math.min.apply(null, list);
      return min + "%";
    },
    sectionDate() {
      if (
        !(
          this.chart1 &&
          this.chart.getModel() &&
          this.netWorth_obj[this.nameKeyList[0]]
        )
      ) {
        return "";
      }
      const key = this.nameLegends.find((item) => item.main == 1).key;
      const start_i = this.chart1.getModel().option.dataZoom[0].startValue;
      const end_i = this.chart1.getModel().option.dataZoom[0].endValue;
      const list = this.netWorth_obj[key].slice(start_i, end_i + 1);
      const min = Math.min.apply(null, list);
      const i = list.findIndex((item) => item == min);
      if (this.xDate[i + start_i]) {
        return `(${this.xDate[i + start_i]})`;
      } else {
        return ``;
      }
    },
    legendIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0];
        if (!list.length) {
          return "--";
        } else {
          return list[list.length - 1] + "%";
        }
      };
    },
    legendAnnualizedIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0];
        if (!list.length || !this.chart || !this.chart.getModel()) return "--";
        const start_i = this.chart
          ? this.chart.getModel().option.dataZoom[0].startValue
          : 0;
        const end_i = this.chart
          ? this.chart.getModel().option.dataZoom[0].endValue
          : list.length - 1;
        const dm = differenceInCalendarMonths(
          this.xDate[end_i],
          this.xDate[start_i]
        )
          ? differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i])
          : 1;
        const yearAnnualizedincomeRate = (list.slice(-1) / (dm / 12)).toFixed(
          2
        );
        return yearAnnualizedincomeRate + "%";
      };
    },
    legendMaxBack() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj2[key])[0];
        if (!list.length) return "--";
        const min = Math.min.apply(null, list);
        return min + "%";
      };
    }
  },
  watch: {
    bulletinBoardList: {
      handler(val) {
        if (val) {
          if (val[0].boardId) {
            console.log("bulletinBoardList:更新视图");
            this.initPage();
          }
        }
      },
      deep: true
    },
    segment: {
      handler(val) {
        if (val || val === 0) {
          console.log("segment:更新视图");
          this.initPage();
        }
      },
      deep: true
    },
    year: {
      handler(val) {
        if (val) {
          console.log("year:更新视图");
          this.initPage();
        }
      },
      deep: true
    },
    showBeyondIncome(val) {
      if (val) {
        this.beyondIncomeHandle(this.beyondIncome_index);
      } else {
        delete this.fitNetWorth_obj["111111"];
        delete this.netWorth_obj["111111"];
        delete this.nameKeyObj["111111"];
        this.nameKeyList.shift();
        this.nameLegends.shift();
        this.chart && this.chart.dispose();
        this.chart1 && this.chart1.dispose();
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj);
        });
      }
    }
  },
  created() {
    this.beyondIncome_index = this.id_index[0];
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart1.dispose();
    this.chart = null;
    this.chart1 = null;
  },
  methods: {
    async initPage(id, dates) {
      const res = [];
      // 请求后台基础数据
      res[0] = await this.getBulletinBoardLine(id, dates);
      // 初始化显示数据和前端存储数据
      (this.xDate = []),
        (this.day_xDate = []),
        (this.fitNetWorth_obj = {}),
        (this.day_fitNetWorth_obj = {}),
        (this.netWorth_obj = {}),
        (this.day_netWorth_obj = {});

      const _legendStatus_isFalse_nameList = [];
      const legendStatus_list = Object.keys(this.legendStatus);
      if (legendStatus_list.length) {
        legendStatus_list.map((key) => {
          if (!this.legendStatus[key]) {
            _legendStatus_isFalse_nameList.push(this.nameKeyObj[key]);
          }
        });
      }
      this.nameKeyObj = {};
      this.nameKeyList = [];
      this.nameLegends = [];
      if (res[0].body.length === 0) {
        return;
      }
      this.isIndexList = res[0].body.lists[0].item
        .filter((e) => e.isIndex)
        .map((e) => e.key);

      res[0].body.lists[0].item
        .map((item) => item.key)
        .map((item, i) => {
          // 用key记录曲线name，规避name重复
          const key = randomStr(8);
          this.nameKeyObj[key] = item;
          this.nameKeyList.push(key);
          if (_legendStatus_isFalse_nameList.indexOf(item) != -1) {
            this.legendStatus[key] = false;
          }
          this.nameLegends.push({
            main: i ? 0 : 1, // 主线为1
            name: item,
            key: key,
            color: this.color_list[i],
            status:
              this.legendStatus[key] != undefined
                ? this.legendStatus[key]
                : true
          });
        });
      if (res[0].body.lists && res[0].body.lists.length > 0) {
        const n_list = [];
        const base_incomeRate_drawDown_list = [];
        res[0].body.lists.forEach((items, index) => {
          this.xDate.push(parseTime(items.date));
          items.item.map((el, i) => {
            el.pnl = el.pnl ? Number(el.pnl) : 0;
            if (n_list[i] == undefined) n_list[i] = 0;
            if (el.isIndex) {
              n_list[i] = (1 + n_list[i]) * (1 + el.pnl) - 1;
            } else {
              if (index > 0) n_list[i] = Number(n_list[i]) + el.pnl;
              // 首次进入页面图例状态 图例只显示主线和指数线
              // if (this.firstInPage == 1 && el.key != this.name1 && index == 0) {
              //   this.legendStatus[this.nameKeyList[i]] = false;
              //   this.nameLegends.find(
              //     (item) => item.name == el.key
              //   ).status = false;
              // }
            }
            el.incomeRate =
              el.netWorth != null ? (n_list[i] * 100).toFixed(2) : null;

            if (!this.fitNetWorth_obj[this.nameKeyList[i]]) {
              this.fitNetWorth_obj[this.nameKeyList[i]] = [];
            }
            if (!this.netWorth_obj[this.nameKeyList[i]]) {
              this.netWorth_obj[this.nameKeyList[i]] = [];
            }
            this.fitNetWorth_obj[this.nameKeyList[i]].push(el.incomeRate);
            if (el.incomeRate == null) {
              this.netWorth_obj[this.nameKeyList[i]][index] = null;
            } else if (
              Number(el.incomeRate) < Number(base_incomeRate_drawDown_list[i])
            ) {
              if (el.isIndex) {
                this.netWorth_obj[this.nameKeyList[i]][index] = (
                  ((el.incomeRate - base_incomeRate_drawDown_list[i]) /
                    (Number(base_incomeRate_drawDown_list[i]) + 100)) *
                  100
                ).toFixed(2);
              } else {
                this.netWorth_obj[this.nameKeyList[i]][index] = (
                  el.incomeRate - base_incomeRate_drawDown_list[i]
                ).toFixed(2);
              }
            } else {
              base_incomeRate_drawDown_list[i] = el.incomeRate;
              this.netWorth_obj[this.nameKeyList[i]][index] = 0;
            }
          });
        });
        this.currentObj1 = this.fitNetWorth_obj;
        this.currentObj2 = this.netWorth_obj;

        this.day_xDate = this.xDate;
        this.day_fitNetWorth_obj = this.fitNetWorth_obj;
        this.day_netWorth_obj = this.netWorth_obj;
        this.dayFreqHandle();
      }
    },

    initChart(obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id));
      this.chart1 = echarts.init(document.getElementById(this.id + "1"));

      let all_list_obj1 = [];
      const series_obj1 = [];
      const series_obj2 = [];

      const start_i = this.chart.getModel()
        ? this.chart.getModel().option.dataZoom[0].startValue
        : 0;
      const end_i = this.chart.getModel()
        ? this.chart.getModel().option.dataZoom[0].endValue
        : obj1[this.nameKeyList[0]].length;
      const view_obj = [{}, {}];

      if (Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          view_obj[0][this.nameKeyObj[key]] = obj1[key].slice(start_i, end_i);
          const item = obj1[key];
          if (
            this.legendStatus[this.nameKeyList[i]] == undefined ||
            this.legendStatus[this.nameKeyList[i]]
          ) {
            all_list_obj1 = [...all_list_obj1, ...item]; // 收集参与y轴计算的数据
          }
          series_obj1.push({
            name: key,
            type: "line",
            symbolSize: 2,
            symbol: "emptyCircle",
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: this.nameLegends[i].color
            },
            data: item,
            connectNulls: true
          });
        });
      }
      const yVal = yAxisNumber(all_list_obj1);

      if (Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          view_obj[1][this.nameKeyObj[key]] = obj2[key].slice(start_i, end_i);
          let _key = key;
          if (
            i == 0 &&
            this.id == "groupManageChart1" &&
            key != Object.keys(obj1)[0]
          ) {
            _key = Object.keys(obj1)[0]; // 解决 分类详情下只有一条策略时，回撤标题为'默认分类'问题  兼容接口代码
          }
          const item = obj2[key];
          series_obj2.push({
            name: _key,
            type: "line",
            symbolSize: 2,
            symbol: "emptyCircle",
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              // color: this.color_list[i]
              color: this.nameLegends[i].color
            },
            // rgba(225,103,86,1)
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color:
                    _key == "风险" || this.nameLegends[i].main || _key != key
                      ? "rgba(225,103,86,0.2)"
                      : "rgba(0,0,0,0)"
                },
                {
                  offset: 1,
                  color:
                    _key == "风险" || this.nameLegends[i].main || _key != key
                      ? "rgba(225,103,86,0.2)"
                      : "rgba(0,0,0,0)"
                }
              ])
            },
            data: item,
            connectNulls: true
          });
          if (this.nameLegends[i].main) {
            series_obj2[i].markLine = {
              // animation: false,
              data: [
                {
                  type: "min"
                }
              ],
              label: {
                show: false
              }
            };
          }
        });
      }
      view_obj[2] = this.xDate.slice(start_i, end_i);
      this.$emit("viewObj", view_obj);

      this.chart.setOption({
        title: {
          left: 52,
          text: "收益",
          top: 10,
          textStyle: {
            color: "#595959",
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            textStyle: {
              color: "#fff"
            }
          },
          formatter: (params) => {
            let str = "";
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`;
            for (let i = 0; i < params.length; i += 1) {
              if (params[i].data != null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${
                        this.nameKeyObj[params[i].seriesName]
                      }</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${
                        params[i].data
                      }%</span>
                      </div>`;
              }
            }
            return str;
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: "6%",
          borderWidth: 0,
          textStyle: {
            color: "#fff"
          }
        },
        legend: {
          show: false,
          orient: "vertical",
          x: "left",
          left: "82%",
          top: "10%",
          textStyle: {
            color: "#90979c",
            fontSize: 11
          },
          formatter: (name) => {
            const start_i = this.chart.getModel().option.dataZoom[0].startValue;
            const end_i = this.chart.getModel().option.dataZoom[0].endValue;
            const obj = this.chart
              .getOption()
              .series.find((item) => item.name == name);
            const dm = differenceInCalendarMonths(
              this.xDate[end_i],
              this.xDate[start_i]
            )
              ? differenceInCalendarMonths(
                  this.xDate[end_i],
                  this.xDate[start_i]
                )
              : 1;
            const yearAnnualizedincomeRate = (
              obj.data[end_i] /
              (dm / 12)
            ).toFixed(2);
            return obj.data[end_i]
              ? this.nameKeyObj[name] +
                  "   " +
                  obj.data[end_i] +
                  "%" +
                  " (年化:" +
                  yearAnnualizedincomeRate +
                  "%)"
              : this.nameKeyObj[name] + "   " + "--";
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [
          {
            show: false,
            type: "category",
            boundaryGap: false, // 折线从x轴起始开始走
            splitNumber: 8,
            axisLine: {
              lineStyle: {
                color: "#90979c"
              }
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
              interval: "auto"
            },
            splitArea: {
              show: false
            },
            axisLabel: {
              show: false,
              interval: "auto"
            },
            data: this.xDate
          }
        ],
        yAxis: [
          {
            type: "value",
            min: yVal[0],
            max: yVal[1],
            interval: yVal[2],
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed"
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#90979c"
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: (value) => {
                return value.toFixed(2) + "%";
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
            zoomLock: true
          },
          {
            show: false,
            brushSelect: false,
            realtime: true, // 实时更新系列的视图
            height: "7%",
            bottom: "1%"
          }
        ],
        series: series_obj1
      });

      this.chart1.setOption({
        title: {
          left: 52,
          text: "回撤",
          top: 10,
          textStyle: {
            color: "#595959",
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            textStyle: {
              color: "#fff"
            }
          },
          formatter: (params) => {
            let str = "";
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`;
            for (let i = 0; i < params.length; i += 1) {
              if (params[i].data != null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${
                        this.nameKeyObj[params[i].seriesName]
                      }</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${
                        params[i].data
                      }%</span>
                      </div>`;
              }
            }
            return str;
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: "37%",
          borderWidth: 0,
          textStyle: {
            color: "#fff"
          }
        },
        legend: {
          show: false,
          orient: "vertical",
          x: "left",
          left: "82%",
          top: "2%",
          textStyle: {
            color: "#90979c",
            fontSize: 11
          },
          formatter: (name) => {
            const start_i =
              this.chart1.getModel().option.dataZoom[0].startValue;
            const end_i = this.chart1.getModel().option.dataZoom[0].endValue;
            const list = this.netWorth_obj[name].slice(start_i, end_i + 1);
            const min = Math.min.apply(null, list);
            return this.nameKeyObj[name] + "   " + min + "%";
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [
          {
            type: "category",
            boundaryGap: false, // 折线从x轴起始开始走
            splitNumber: 8,
            axisLine: {
              show: false,
              lineStyle: {
                color: "#90979c"
              }
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false,
              alignWithLabel: true,
              interval: "auto"
            },
            splitArea: {
              show: false
            },
            axisLabel: {
              interval: "auto",
              margin: 20
            },
            data: this.xDate
          }
        ],
        yAxis: [
          {
            type: "value",
            splitNumber: 4,
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed"
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#90979c"
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: (value) => {
                return value + "%";
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
            zoomLock: true
          },
          {
            brushSelect: false,
            realtime: true, // 实时更新系列的视图
            height: "14%",
            bottom: "1%"
          }
        ],
        series: series_obj2
      });

      if (this.typePage == "groupManage" && this.name1 == "组合") {
        // 对比页面
        this.$emit("loadingOk");
      }

      this.chart.on(
        "datazoom",
        debounce(() => {
          const baseline_i =
            this.chart.getModel().option.dataZoom[0].startValue;
          const end_i = this.chart.getModel().option.dataZoom[0].endValue;
          let op = this.chart.getOption();
          let op1 = this.chart1.getOption();
          const op_res = xReturnZeroFristPage(
            this.fitNetWorth_obj,
            this.netWorth_obj,
            op,
            op1,
            baseline_i,
            end_i,
            this.isIndexList
          );
          op = op_res.op;
          op1 = op_res.op1;

          // 风险指标
          const view_obj = [{}, {}];
          this.currentObj1 = {};
          this.currentObj2 = {};
          Object.keys(this.fitNetWorth_obj).forEach((key) => {
            const _obj1 = op.series.filter((item) => item.name == key)[0];
            const _obj2 = op1.series.filter((item) => item.name == key)[0];
            view_obj[0][this.nameKeyObj[key]] = _obj1.data.slice(
              baseline_i,
              end_i + 1
            );
            view_obj[1][this.nameKeyObj[key]] = _obj2.data.slice(
              baseline_i,
              end_i + 1
            );

            this.currentObj1[key] = view_obj[0][this.nameKeyObj[key]];
            this.currentObj2[key] = view_obj[1][this.nameKeyObj[key]];
          });
          view_obj[2] = this.xDate.slice(baseline_i, end_i + 1);
          this.$emit("viewObj", view_obj);

          const yVal = yAxisNumber(op_res.all_list_obj1);
          op.yAxis[0].min = yVal[0];
          op.yAxis[0].max = yVal[1];
          op.yAxis[0].interval = yVal[2];
          op1.dataZoom[0].start = op.dataZoom[0].start;
          op1.dataZoom[0].end = op.dataZoom[0].end;
          op1.dataZoom[1].start = op.dataZoom[1].start;
          op1.dataZoom[1].end = op.dataZoom[1].end;
          this.chart.setOption(op);
          this.chart1.setOption(op1);
        }, 500)
      );

      this.chart1.on(
        "datazoom",
        debounce(() => {
          const baseline_i =
            this.chart1.getModel().option.dataZoom[0].startValue;
          const end_i = this.chart1.getModel().option.dataZoom[0].endValue;
          let op = this.chart.getOption();
          let op1 = this.chart1.getOption();
          const op_res = xReturnZeroFristPage(
            this.fitNetWorth_obj,
            this.netWorth_obj,
            op,
            op1,
            baseline_i,
            end_i,
            this.isIndexList
          );
          op = op_res.op;
          op1 = op_res.op1;

          // 风险指标 & 获取当前显示的数据
          const view_obj = [{}, {}];
          this.currentObj1 = {};
          this.currentObj2 = {};
          Object.keys(this.fitNetWorth_obj).forEach((key) => {
            const _obj1 = op.series.filter((item) => item.name == key)[0];
            const _obj2 = op1.series.filter((item) => item.name == key)[0];
            view_obj[0][this.nameKeyObj[key]] = _obj1.data.slice(
              baseline_i,
              end_i + 1
            );
            view_obj[1][this.nameKeyObj[key]] = _obj2.data.slice(
              baseline_i,
              end_i + 1
            );

            this.currentObj1[key] = view_obj[0][this.nameKeyObj[key]];
            this.currentObj2[key] = view_obj[1][this.nameKeyObj[key]];
          });
          view_obj[2] = this.xDate.slice(baseline_i, end_i + 1);
          this.$emit("viewObj", view_obj);

          const yVal = yAxisNumber(op_res.all_list_obj1);
          op.yAxis[0].min = yVal[0];
          op.yAxis[0].max = yVal[1];
          op.yAxis[0].interval = yVal[2];
          op.dataZoom[0].start = op1.dataZoom[0].start;
          op.dataZoom[0].end = op1.dataZoom[0].end;
          op.dataZoom[1].start = op1.dataZoom[1].start;
          op.dataZoom[1].end = op1.dataZoom[1].end;
          this.chart.setOption(op);
          this.chart1.setOption(op1);
        }, 500)
      );

      this.chart.on("legendselectchanged", (obj) => {
        let op = this.chart.getOption();
        let op1 = this.chart1.getOption();
        op1.legend[0].selected = obj.selected;

        // 记录图例状态
        this.savaLegendStatus(obj.selected);

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue;
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue;
        const op_res = xReturnZeroFristPage(
          this.fitNetWorth_obj,
          this.netWorth_obj,
          op,
          op1,
          baseline_i,
          end_i,
          this.isIndexList
        );
        op = op_res.op;
        op1 = op_res.op1;
        const yVal = yAxisNumber(op_res.all_list_obj1);
        op.yAxis[0].min = yVal[0];
        op.yAxis[0].max = yVal[1];
        op.yAxis[0].interval = yVal[2];
        this.chart.setOption(op);
        this.chart1.setOption(op1);
      });

      this.chart1.on("legendselectchanged", (obj) => {
        let op = this.chart.getOption();
        let op1 = this.chart1.getOption();
        op.legend[0].selected = obj.selected;

        // 记录图例状态
        this.savaLegendStatus(obj.selected);

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue;
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue;
        const op_res = xReturnZeroFristPage(
          this.fitNetWorth_obj,
          this.netWorth_obj,
          op,
          op1,
          baseline_i,
          end_i,
          this.isIndexList
        );
        op = op_res.op;
        op1 = op_res.op1;
        const yVal = yAxisNumber(op_res.all_list_obj1);
        op.yAxis[0].min = yVal[0];
        op.yAxis[0].max = yVal[1];
        op.yAxis[0].interval = yVal[2];
        this.chart.setOption(op);
        this.chart1.setOption(op1);
      });

      this.chart.on("highlight", (params) => {
        const obj = params.batch[0];
        this.chart1.dispatchAction({
          type: "showTip",
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        });
      });
      this.chart1.on("highlight", (params) => {
        const obj = params.batch[0];
        this.chart.dispatchAction({
          type: "showTip",
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        });
      });

      this.chart.on("globalout", () => {
        this.chart1.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: -1
        });
      });
      this.chart1.on("globalout", () => {
        this.chart.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: -1
        });
      });

      this.firstInPage++;
      // }, 100, { 'leading': false, 'trailing': true }),
    },

    beyondIncomeHandle(val) {
      if (!val) return;
      const name1 = this.name1;
      const name2 = this.indexNames.find((item) => item.id == val).name;
      const key1 = this.nameLegends.find((item) => item.name == name1).key;
      const key2 = this.nameLegends.find((item) => item.name == name2).key;
      this.nameKeyObj["111111"] = "超额收益";
      if (this.nameKeyList[0] != "111111") this.nameKeyList.unshift("111111");
      if (this.nameLegends[0].key != "111111") {
        this.nameLegends.unshift({
          color: "#F6BD16",
          key: "111111",
          name: "超额收益",
          status: true
        });
      }
      this.fitNetWorth_obj["111111"] = [];
      this.netWorth_obj["111111"] = [];
      let base_val = 0;
      this.fitNetWorth_obj[key1].forEach((e, i) => {
        if (e != null && this.fitNetWorth_obj[key2][i] != null) {
          const num = (e - this.fitNetWorth_obj[key2][i]).toFixed(2);
          this.fitNetWorth_obj["111111"].push(num);
          if (Number(num) > base_val) {
            base_val = Number(num);
            this.netWorth_obj["111111"].push(0);
          } else {
            this.netWorth_obj["111111"].push((num - base_val).toFixed(2));
          }
        } else {
          this.fitNetWorth_obj["111111"].push(null);
          this.netWorth_obj["111111"].push(null);
        }
      });
      this.chart && this.chart.dispose();
      this.chart1 && this.chart1.dispose();
      this.$nextTick(() => {
        this.initChart(this.fitNetWorth_obj, this.netWorth_obj);
      });
    },

    legendHandle(name) {
      this.chart.dispatchAction({
        type: "legendToggleSelect",
        name
      });
    },

    // 日频
    dayFreqHandle() {
      this.xDate = this.day_xDate;
      this.fitNetWorth_obj = this.day_fitNetWorth_obj;
      this.netWorth_obj = this.day_netWorth_obj;
      // 如果超额曲线显示且对应指数也存在, 则保留超额曲线
      if (
        this.showBeyondIncome &&
        this.id_index.indexOf(this.beyondIncome_index) != -1
      ) {
        this.beyondIncomeHandle(this.beyondIncome_index);
      } else {
        this.chart && this.chart.dispose();
        this.chart1 && this.chart1.dispose();
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj);
        });
      }
    },

    // 收益与回撤pnl
    async getBulletinBoardLine() {
      const res = await getBulletinBoardLine({
        userId: this.userId,
        segment: this.segment,
        year: this.year,
        boardId: this.bulletinBoardList[0].boardId
          ? this.bulletinBoardList[0].boardId
          : ""
      });
      return res;
    },

    // 记录图例状态
    savaLegendStatus(obj) {
      this.legendStatus = {};
      Object.keys(obj).map((key) => {
        const status = obj[key];
        if (!status) this.legendStatus[key] = status;
      });
    },
    // 删除看板
    delBoard() {
      delBoard({
        boardId: this.bulletinBoardList[0].boardId
          ? this.bulletinBoardList[0].boardId
          : ""
      })
        .then((res) => {
          this.$message({
            type: "success",
            message: res.body,
            duration: 2000
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 选择看板曲线
    addHandle() {
      if (this.strategyList.length >= 10) {
        this.$message({
          message: "看板最多添加10条数据",
          warning: "warning"
        });
        return;
      }
      this.$emit("addTabsBullet", this.bulletinBoardList[0]);
    },
    checkStatus(val) {
      val.status = !val.status;
      this.legendHandle(val.key);
      // console.log(val);
    }
  }
};
</script>

<style lang="scss" scoped>
.incomeRateChart {
  .chart {
    width: calc(100% - 432px);
    position: relative;
    .tip {
      position: absolute;
      bottom: 80px;
      left: calc(100% - 180px);
      color: #666;
      p {
        text-align: right;
      }
    }
  }
  .control {
    display: flex;
    flex-direction: column;
    margin-left: 24px;
    .beyondIncome {
      .shortline {
        width: 20px;
        border: 1px solid #d9d9d9;
      }
    }
    .legend {
      min-width: 432px;
      height: 100%;
      overflow: auto;
      background: #fafafa;
      border-radius: 8px;
      .card {
        min-height: 48px;
        cursor: pointer;
        padding: 16px 26px 12px 16px;
        box-shadow: inset 0px -1px 0px 0px #f0f0f0;
        &:hover {
          background: #ffffff;
          box-shadow: inset 0px -1px 0px 0px #f0f0f0;
        }
      }
    }
    .legend {
      min-width: 432px;
      height: 100%;
      overflow: auto;
      background: #fafafa;
      border-radius: 8px;
      .card {
        height: 48px;
        cursor: pointer;
        padding: 0 13px 0 14px;
        box-shadow: inset 0px -1px 0px 0px #f0f0f0;
        &:hover {
          background: #ffffff;
          box-shadow: inset 0px -1px 0px 0px #f0f0f0;
        }
        .legend-name {
          .line {
            width: 28px;
            margin-left: 10px;
          }
        }
        .right {
          font-size: 12px;
          color: #8c8c8c;
          p {
            text-align: right;
          }
        }
      }
    }
    .mt16 {
      margin-top: 16px;
    }
    .left {
      font-size: 12px;
      color: #8c8c8c;
    }
    // .legend-name {
    //   font-size: 14px;
    //   font-weight: 500;
    //   color: #262626;
    //   .line {
    //     width: 35px;
    //     margin-top: 3px;
    //   }
    // }
  }
}
</style>
